<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Show_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('module_helper');
		//$this->load->library('music');
		//$this->load->library('country_city');
	}

	function list_opening(){
		$where = "status = 'opening' ";
		$total = count( $this->db->where($where)->get(TBL_SHOW)->result() );
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/show/opening/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	 
		$records = $this->db->where($where)->order_by('id','desc')->limit($records_per_page, $per_page )->get(TBL_SHOW)->result();
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function list_pending(){
		$where = "status = 'pending' ";
		$total = count( $this->db->where($where)->get(TBL_SHOW)->result() );
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/show/pending/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	 
		$records = $this->db->where($where)->order_by('id','desc')->limit($records_per_page, $per_page )->get(TBL_SHOW)->result();
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function list_closed(){
		$where = "status = 'closed' ";
		$total = count( $this->db->where($where)->get(TBL_SHOW)->result() );
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/show/closed/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	 
		$records = $this->db->where($where)->order_by('id','desc')->limit($records_per_page, $per_page )->get(TBL_SHOW)->result();
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function list_cancelled(){
		$where = "status = 'cancelled' ";
		$total = count( $this->db->where($where)->get(TBL_SHOW)->result() );
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/show/cancelled/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	 
		$records = $this->db->where($where)->order_by('id','desc')->limit($records_per_page, $per_page )->get(TBL_SHOW)->result();
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function search(){
		$s = ($_GET['key']);
		$filter = ($_GET['filter']);
		$options = array('acc_code'=>'Account Code','ref_no'=>'Show ref','name'=>'Show name', 'artist'=>'Artist');
		if(!in_array($filter, array_keys($options))){
			$filter = 'acc_code';
		}
		
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		if($filter == 'acc_code'){
			$total = count( $this->db->select("TBLSHOW.*")
								->from(TBL_SHOW." AS TBLSHOW")
								->join(TBL_ACCOUNT." AS TBLACCOUNT","TBLSHOW.user_created_id=TBLACCOUNT.id")
								->where("TBLACCOUNT.acc_code",$s)
								->get()->result()
								);
		}else{
			$total = count( $this->db->where(array("$filter"=>$s))->get(TBL_SHOW)->result() );
		}
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/show/search/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit = $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	if($filter == 'acc_code'){
			$records = $this->db->select("TBLSHOW.*")
								->from(TBL_SHOW." AS TBLSHOW")
								->join(TBL_ACCOUNT." AS TBLACCOUNT","TBLSHOW.user_created_id=TBLACCOUNT.id")
								->where("TBLACCOUNT.acc_code",$s)
								->order_by('TBLSHOW.id','desc')
								->limit($records_per_page, $per_page )
								->get()
								->result();
					
		}else{ 
			$records = $this->db->where(array("$filter"=>$s))->order_by('id','desc')->limit($records_per_page, $per_page )->get(TBL_SHOW)->result();
		}
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	
	function change_show_status(){
		$SHOW = $this->show_entity->init('id',$_POST['show_id']);
		$SHOW->setStatus($_POST['status']);
		$SHOW->update();
		if($_POST['status'] == 'opening'){
			$this->crontab_email->cronUpdate(strval("SHOW-ADD-NOTIFY_BUYERS".$SHOW->getRefNo()),'_sendEmailToBuyers_notifyNewShow', strval($SHOW->getRefNo()), array(time()) );
			$time_proc = 86400+ $SHOW->getBidDueDate();
			$this->crontab_email->cronUpdate(strval("NOTIFY_SELLER_BID_CLOSED".$SHOW->getRefNo()),'_sendEmailToUser_notifySellerBidClosed', strval($SHOW->getRefNo()), array( $time_proc ) );
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function delete(){
		$SHOW = $this->show_entity->init('id',$_POST['show_id']);
		$this->db->where('show_ref_no',$SHOW->getRefNo())->delete(TBL_BOOKING_FOR);
		$this->db->where('show_ref_no',$SHOW->getRefNo())->delete(TBL_BID);
		$this->db->where('ref_no',$SHOW->getRefNo())->delete(TBL_SHOW);
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function submit_information(){
		$SHOW = clone_( $this->show_entity->init('id', $this->input->post('show_id','')) );
		$USER = $this->user_entity->init('id', $SHOW->getUserCreatedId());
		cleanFilesNotUsed($USER->getId());
		
		$error_array = array();
		
		$start_date = convertToTimeStampFromFormat($format = "d-F-Y", $str=$this->input->post('start_date',''));
		$end_date = convertToTimeStampFromFormat($format = "d-F-Y", $str=$this->input->post('end_date',''));
		$bid_due_date = convertToTimeStampFromFormat($format = "d-F-Y", $str=$this->input->post('bid_due_date',''));
	
		if(empty($_POST['show_name'])){
			$error_array[] = 'show_name';
		}
		
		if(empty($_POST['artist'])){
			$error_array[] = 'artist';
		}
		
		if(empty($_POST['bid_open'])){
			$error_array[] = 'bid_open';
		}
		
	//	if(empty($_POST['music_genre'])){
	//		$error_array[] = 'music_genre';
	//	}
		
	//	if(empty($_POST['speaker_profile'])){
	//		$error_array[] = 'speaker_profile';
	//	}
		
	//	if(empty($_POST['plays_musicals'])){
	//		$error_array[] = 'plays_musicals';
	//	}
		
	//	if($start_date == 0 || $end_date == 0 || $bid_due_date == 0 || $start_date>$end_date || $end_date < time() ){
	//		$error_array[] = 'period';
	//	}  
		
	//	if( $bid_due_date > $start_date || $bid_due_date < time() ){
	//		$error_array[] = 'bid_due_date';
	//	}
		
		if(empty($_POST['available_for'])){
			$error_array[] = 'available_for';
		}
		
		if(!is_integer(intval($_POST['entourage_no'])) || $_POST['entourage_no'] <= 0){
			$error_array[] = 'entourage_no';
		}
		
		if(!is_numeric($_POST['min_bid']) || $_POST['min_bid'] <= 0){
			$error_array[] = 'min_bid';
		}
		
	//	if(empty($_POST['additional'])){
	//		$error_array[] = 'additional';
	//	}
		
		$tech_rider = $SHOW->getTechRider();
		$show_image_1 = $SHOW->getShowImage1();
		$show_image_2 = $SHOW->getShowImage2();
		$show_image_3 = $SHOW->getShowImage3();
		$hospitality_rider = $SHOW->getHospitalityRider();
		
		if(isset($_FILES["tech_rider"]) AND !empty($_FILES["tech_rider"]['name'])) {
			if(($_FILES["tech_rider"]['size']/1000000) > allowMaxFileSize() ){
				$tech_rider = '';
			}else{
				$tech_rider = $this->module_helper->uploadFile( 
										$_FILES["tech_rider"]['tmp_name'],
										$_FILES["tech_rider"]['name'],
										$USER->getFolderFileStorage(),
										allowExtensionFileDocumentUpload()
									);
			}	
		}
		
		if(isset($_FILES["show_image_1"]) AND !empty($_FILES["show_image_1"]['name'])) {
			if(($_FILES["show_image_1"]['size']/1000000) > allowMaxFileSize() ){
				$show_image_1 = '';
			}else{
				$show_image_1 = $this->module_helper->uploadFile( 
										$_FILES["show_image_1"]['tmp_name'],
										$_FILES["show_image_1"]['name'],
										$USER->getFolderFileStorage(),
										allowExtensionPictureUpload()
									);
			}	
		}
		
		if(isset($_FILES["show_image_2"]) AND !empty($_FILES["show_image_2"]['name'])) {
			if(($_FILES["show_image_2"]['size']/1000000) > allowMaxFileSize() ){
				$show_image_2 = '';
			}else{
				$show_image_2 = $this->module_helper->uploadFile( 
										$_FILES["show_image_2"]['tmp_name'],
										$_FILES["show_image_2"]['name'],
										$USER->getFolderFileStorage(),
										allowExtensionPictureUpload()
									);
			}
		}
		
		if(isset($_FILES["show_image_3"]) AND !empty($_FILES["show_image_3"]['name'])) {
			if(($_FILES["show_image_3"]['size']/1000000) > allowMaxFileSize() ){
				$show_image_3 = '';
			}else{
				$show_image_3 = $this->module_helper->uploadFile( 
										$_FILES["show_image_3"]['tmp_name'],
										$_FILES["show_image_3"]['name'],
										$USER->getFolderFileStorage(),
										allowExtensionPictureUpload()
									);
			}
		}
		
		if(isset($_FILES["hospitality_rider"]) AND !empty($_FILES["hospitality_rider"]['name'])) {
			if(($_FILES["hospitality_rider"]['size']/1000000) > allowMaxFileSize() ){
				$hospitality_rider = '';
			}else{
				$hospitality_rider = $this->module_helper->uploadFile( 
										$_FILES["hospitality_rider"]['tmp_name'],
										$_FILES["hospitality_rider"]['name'],
										$USER->getFolderFileStorage(),
										allowExtensionFileDocumentUpload()
									);
			}	
		}
		
		if(empty($tech_rider)){
			$error_array[] = 'tech_rider';
		}	
		if(empty($show_image_1) AND empty($show_image_2) AND empty($show_image_3)){
			$error_array[] = 'show_image';
		}
		if(!empty($_FILES["hospitality_rider"]['tmp_name']) AND empty($hospitality_rider)){
			$error_array[] = 'hospitality_rider';
		}
		
		if(!empty($error_array)){
			echo "err#".implode("#",$error_array);
			exit();
		}else{
			$revision = $SHOW->buildNewRevision();
			
			$array_init = array('speaker_profile', 'plays_musicals', 'music_genre', 'bid_open', 'available_for');
			foreach($array_init as $element){
				if(!isset($_POST[$element])){
					$_POST[$element] = array();
				}
			}
			
			$SHOW->setName($this->input->post('show_name',''));
			$SHOW->setShowType($this->input->post('show_type',''));
			$SHOW->setShowDuration($this->input->post('show_duration',''));
			$SHOW->setBidType(implode(',', $_POST['bid_open']));
			$SHOW->setArtist($this->input->post('artist',''));
			$SHOW->setCountryOriginCode($_POST['country_origin']);
			$SHOW->setMusicGenre(implode(',', $_POST['music_genre']));
			$SHOW->setSpeakerProfile(implode(',', $_POST['speaker_profile']));
			$SHOW->setPlaysMusicals(implode(',', $_POST['plays_musicals']));
			$SHOW->setStartDate($start_date);
			$SHOW->setEndDate($end_date);
			$SHOW->setBidDueDate($bid_due_date);
			$SHOW->setAvailableFor(implode(',',$_POST['available_for']));
			$SHOW->setEntourageNo(intval($_POST['entourage_no']));
			$SHOW->setMinBid($_POST['min_bid']);
			$SHOW->setAirTravel($_POST['air_travel']);
			$SHOW->setGround($_POST['ground']);
			$SHOW->setHotel($_POST['hotel']);
			$SHOW->setPerDiem($_POST['per_diem']);
			$SHOW->setLightAndSound($_POST['light_n_sound']);
			$SHOW->setRiderReq($_POST['rider_req']);
			$SHOW->setVisaAndWorkPermits($_POST['visa_n_work_permits']);
			$SHOW->setAdditional($this->input->post('additional',''));
			$SHOW->setTechRider($tech_rider);
			$SHOW->setShowImage1($show_image_1);
			$SHOW->setShowImage2($show_image_2);
			$SHOW->setShowImage3($show_image_3);
			$SHOW->setHospitalityRider($hospitality_rider);
			$SHOW->setCreatedTime(time());
			
			$SHOW->setRevision($revision);
			$SHOW->update();
			
			$this->session->set_flashdata('success', lang('dataman.success'));
			echo 'ok#';
			exit();
		}	
	}
	
	function bid(){
		$SHOW = $this->show_entity->init('id', intval($_GET['show_id']));
		return $this->db->where('show_ref_no', $SHOW->getRefNo())->get(TBL_BID)->result();
	}
	
	function change_bid_status(){
		$BID = $this->bid_entity->init('id', $_POST['bid_id']);
		$USER = $this->user_entity->init('acc_code', $BID->getAccountCode());
		$SHOW = $this->show_entity->init('ref_no', $BID->getShowRefNo());
		
		$status = $_POST['status'];
		
		if($status == 'won'){
			$SHOW->setUserBidWon($USER->getId());	
			$SHOW->setStatus('closed');
		}else{
			$SHOW->setUserBidWon(NULL);	
			$SHOW->setStatus('opening');
		}
		$SHOW->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo site_url("admin/dataman/show/bid/?show_id=".$SHOW->getId());
		exit();
	}
	
	function delete_bid(){
		$BID = $this->bid_entity->init('id', $_POST['bid_id']);
		
		$this->db->where(array(	'account_code'=>$BID->getAccountCode(), 'show_ref_no'=>$BID->getShowRefNo()))->delete(TBL_BID);
		$this->db->where(array(	'account_code'=>$BID->getAccountCode(), 'show_ref_no'=>$BID->getShowRefNo()))->delete(TBL_BOOKING_FOR);
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function bid_information(){
		$BID = $this->bid_entity->init('id', $_POST['bid_id']);
		$SHOW = $this->show_entity->init('ref_no', $BID->getShowRefNo());
		$booking_records = $this->db->where( array('account_code'=>$BID->getAccountCode(), 'show_ref_no'=>$BID->getShowRefNo()) )->get(TBL_BOOKING_FOR)->result();
		return array('show'=>$SHOW, 'bid'=> $BID, 'booking'=>$booking_records);
	}
	
	function edit_bid(){
		$BID = $this->bid_entity->init('id', $_POST['bid_id']);
		$SHOW = $this->show_entity->init('ref_no', $BID->getShowRefNo());
		$booking_records = $this->db->where( array('account_code'=>$BID->getAccountCode(), 'show_ref_no'=>$BID->getShowRefNo()) )->get(TBL_BOOKING_FOR)->result();
		return array('show'=>$SHOW, 'bid'=> $BID, 'booking'=>$booking_records);
	}
	
	function submit_edit_bid(){
		$BID = $this->bid_entity->init( 'id', intval($_POST['bid_id']) );
		$USER_ACC = $this->user_entity->init('acc_code', $BID->getAccountCode() );
		$SHOW = $this->show_entity->init('ref_no', $BID->getShowRefNo() );
		
		$howManyBookingItems = count($_POST['booking_for']);
		$howManyBookingItemsExisted = count($_POST['edit_id']);
		
		$booking_records = $this->db->where( array('account_code'=>$BID->getAccountCode(), 'show_ref_no'=>$BID->getShowRefNo()) )->get(TBL_BOOKING_FOR)->result();
		$book_old_arr = array();
		foreach($booking_records as $book_obj){
			$book_old_arr[] = $book_obj->id;
		}
		$book_new_arr = array_values($_POST['edit_id']);
		
		$book_will_remove = array_diff($book_old_arr, $book_new_arr);
		foreach($book_will_remove as $item_id){
			$this->db->where('id', $item_id)->delete(TBL_BOOKING_FOR);
		}
		
		for($i = 0; $i< $howManyBookingItems; $i++){
			if($i< $howManyBookingItemsExisted ){ // edit item
				$BOOKING = $this->booking_entity->init('id',$_POST['edit_id'][$i]);
			}else{ // add new item
				$newBookingId = $this->booking_entity->createNewBookingEntity($USER_ACC->getAccCode(), $SHOW->getRefNo() );
				$BOOKING = $this->booking_entity->init('id',$newBookingId);
			}
		
			$BOOKING->setBookingFor($_POST['booking_for'][$i]);
			$BOOKING->setCountry($_POST['country'][$i]);
			$BOOKING->setCity($_POST['city'][$i]);
			$BOOKING->setVenue($_POST['venue'][$i]);
			$BOOKING->setAddress($_POST['address'][$i]);
			$BOOKING->setCapacity($_POST['capacity'][$i]);
			$BOOKING->setTicketPrice($_POST['ticket_pricing'][$i]);
			$BOOKING->setPotentialSponsors($_POST['potential_sponsors'][$i]);
			
			$BOOKING->update();
		}
	
		$BID->setOfferPrice($this->input->post('offer_price',0));
		$BID->setArtistProduction1($this->input->post('artist_production1',''));
		$BID->setArtistProduction2($this->input->post('artist_production2',''));
		$BID->setArtistProduction3($this->input->post('artist_production3',''));
		$BID->setArtistProduction4($this->input->post('artist_production4',''));		
		$BID->setYear1($this->input->post('year1',0));
		$BID->setYear2($this->input->post('year2',0));
		$BID->setYear3($this->input->post('year3',0));
		$BID->setYear4($this->input->post('year4',0));
		$BID->setCapacity1($this->input->post('capacity1',''));	
		$BID->setCapacity2($this->input->post('capacity2',''));	
		$BID->setCapacity3($this->input->post('capacity3',''));	
		$BID->setCapacity4($this->input->post('capacity4',''));	
		$BID->setVenue1($this->input->post('venue1',''));
		$BID->setVenue2($this->input->post('venue2',''));
		$BID->setVenue3($this->input->post('venue3',''));
		$BID->setVenue4($this->input->post('venue4',''));
		$BID->setDateBid(time());
		
		$BID->update();
		
		//send email
		//$this->crontab_email->cronUpdate(strval($USER_EXISTED->getAccCode()),'_sendEmailToUser_editAccNotify', strval($USER_EXISTED->getId()), strval(time()) );
		//$this->crontab_email->cronExec( strval($USER_EXISTED->getAccCode()) );
		$this->session->set_flashdata('success', lang('dataman.success'));	
		echo 'ok';
		exit();
	}
	
	
	
	
	
	
	
	
}
